﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SomeRandomGame.Interfaces;

namespace SomeRandomGame.Graphics
{
    public class ParallaxingBackgroundLayer: IDrawableObject
    {
        private Texture2D _texture;
        private Vector2[] _positions;
        private readonly int _moveSpeed;
        private readonly int _screenWidth;
        private readonly String _texturePath;

        public ParallaxingBackgroundLayer( int moveSpeed, int screenWidth, String texturePath )
        {
            _moveSpeed = moveSpeed;
            _screenWidth = screenWidth;
            _texturePath = texturePath;
        }

        public Vector2 Position
        {
            get { return new Vector2( 0, 0 ); }
            set
            {
                throw new InvalidOperationException( "Cant change position of a background layer!" );
            }
        }

        public int Width { get { return _texture.Width; } }
        public int Height { get { return _texture.Height; } }
        public bool Active { get { return true; } }

        public void Initialize( IGameManager gameManager )
        {
            _texture = gameManager.Game.Content.Load<Texture2D>( _texturePath );

            // If we divide the screen with the texture width then we can determine the number of tiles need.
            // We add 1 to it so that we won't have a gap in the tiling
            _positions = new Vector2[_screenWidth / _texture.Width + 1];

            for( int i = 0; i < _positions.Length; i++ )
            {
                _positions[i] = new Vector2( i * _texture.Width, 0 );
            }
        }

        public void Update( IGameManager gameManager )
        {
            for( int i = 0; i < _positions.Length; i++ )
            {
                _positions[i].X += _moveSpeed;

                if( _moveSpeed <= 0 )
                {
                    if( _positions[i].X <= -_texture.Width )
                    {
                        _positions[i].X = _texture.Width * ( _positions.Length - 1 );
                    }
                }
                else
                {
                    if( _positions[i].X >= _texture.Width * ( _positions.Length - 1 ) )
                    {
                        _positions[i].X = -_texture.Width;
                    }
                }
            }
        }

        public void Draw( SpriteBatch spriteBatch, IGameManager gameManager, GameTime gameTime )
        {
            spriteBatch.Begin();
            foreach( Vector2 position in _positions )
            {
                spriteBatch.Draw( _texture, position, Color.White );
            }
            spriteBatch.End();
        }
    }
}
